import { useState, useEffect, useRef } from "react";
import { Form, message, Modal } from "antd";

import request from "@/utils/request";
import { IForm } from "@/components";
import { transformTreeData /*getAllParentIds*/ } from "@/utils/util";
import { useAppSelector } from "@/utils/hooks";

import type { FormItemConfig } from "@/components/FormItem/type";
import { RecordItem, Params, type RecordDetail } from "../type";
import ResourceForm from "@/views/AuthManage/ResourceManage/ResourceForm";

interface Props {
	open: boolean;
	record?: ResourceNode;
	onCancel: () => void;
	onSearch: (params: Params) => void;
}

const AddModal: React.FC<Props> = ({ open, onCancel, record, onSearch }) => {
	const [app] = useAppSelector(state => [state.app]);
	const [form] = Form.useForm();
	const [resources, setResources] = useState<DataNode[]>([]);
	const [initialResources, setInitialResources] = useState<string[]>([]);
	const [detail, setDetail] = useState<RecordDetail>();

	const resourceFormRef = useRef<any>(null);

	useEffect(() => {
		if (open) {
			setDetail({parentId: record?.id ? Number(record.id) : 0} as RecordDetail);
		}
	}, [open]);

	const handleOk = async () => {
		try {
			const { ...rest } = await resourceFormRef.current.validateFields();
			console.log(rest);
			// const pIds = getAllParentIds(resources, resourceIds)
			const data = {
				...rest
			};
			request("resourceManageAdd", { data }).then(res => {
				if (res.code === 0) {
					message.success("添加成功");
					onSearch({} as Params);
					handleCancel();
				}
			});
		} catch (error) {
			message.warn("信息录入有误");
		}
	};

	const handleCancelClick = () => {
		return handleCancel();
	};

	const handleCancel = () => {
		form.resetFields();
		setResources([]);
		setInitialResources([]);
		onCancel();
	};

	return (
		<Modal
			title="添加菜单"
			open={open}
			width={660}
			destroyOnClose
			maskClosable={false}
			onOk={handleOk}
			onCancel={handleCancelClick}
		>
			<ResourceForm ref={resourceFormRef} selRecord={detail}></ResourceForm>
		</Modal>
	);
};

export default AddModal;
